using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using MultiAgentsServer.Scripts.Database;
using MultiAgentsServer.Scripts.Shared;
using static MultiAgentsServer.Scripts.Shared.ModelConsts;

namespace MultiAgentsServer.Pages;

[Authorize]
public class UserPermissionManagementModel : PageModel
{
    private readonly DataBaseOperationService _dbOperationService;

    public UserPermissionManagementModel(DataBaseOperationService dataBaseOperationService)
    {
        _dbOperationService = dataBaseOperationService;

        GptModelList = ModelNames;
        UserList = _dbOperationService.GetUserList();
    }

    public List<string> GptModelList { get; private set; }

    public List<UserDB> UserList { get; private set; }

    public void OnGet() { }

    public IActionResult OnPostSaveUserPermissions([FromForm] SavePermissionsRequest request)
    {
        if (request != null && request.UserId != 0)
        {
            _dbOperationService.SaveUserPermissions(
                request.UserId,
                request.AccessChatModels,
                request.AccessWorkflowModels
            );

            ViewData["Success"] = "Permissions saved successfully!";

            return RedirectToPage("UserPermissionManagement");
        }
        else
        {
            ViewData["Error"] = "Failed to save permissions.";

            return RedirectToPage("UserPermissionManagement");
        }
    }

    public IActionResult OnPostDeleteUserPermissions([FromForm] int UserId)
    {
        if (UserId != 0)
        {
            _dbOperationService.DeleteUserById(UserId);
            ViewData["Success"] = "Permissions deleted successfully!";
            return RedirectToPage("UserPermissionManagement");
        }
        else
        {
            ViewData["Error"] = "Failed to delete permissions.";
            return RedirectToPage("UserPermissionManagement");
        }
    }

    public class SavePermissionsRequest
    {
        public int UserId { get; set; }
        public List<string> AccessChatModels { get; set; } = [];
        public List<string> AccessWorkflowModels { get; set; } = [];
    }
}